package com.lagou.service;

import com.lagou.common.constant.Constants;
import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ServiceRegistry implements Watcher{

    private CountDownLatch latch = new CountDownLatch(1);

    private String registryAddress;

    public ServiceRegistry(String registryAddress) {
        this.registryAddress = registryAddress;
    }

    public void register(String data) {
        if (data != null) {
            ZooKeeper zk = connectServer();
            if (zk != null) {
                createNode(zk, data);
            }
        }
    }

    /**
     * 连接 zookeeper 服务器
     * @return
     */
    private ZooKeeper connectServer() {
        ZooKeeper zk = null;
        try {
            zk = new ZooKeeper(registryAddress, Constants.ZK_SESSION_TIMEOUT, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if (event.getState() == Event.KeeperState.SyncConnected) {
                        latch.countDown();
                    }
                }
            });
            latch.await();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return zk;
    }

    /**
     * 创建节点
     * @param zk
     * @param data
     */
    private void createNode(ZooKeeper zk, String data) {
        try {
            byte[] bytes = data.getBytes();
            String path = zk.create(Constants.ZK_DATA_PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            System.out.println("创建Znode节点，路径为："+path+"；数据为 => {"+data+"}");
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        Event.KeeperState zkState = watchedEvent.getState();
        String path = watchedEvent.getPath();
        Event.EventType eventType = watchedEvent.getType();

        if(zkState == Event.KeeperState.SyncConnected){
            if(eventType == Event.EventType.None){
                //连接建立事件
                System.out.println("建立zookeeper连接成功!");
                latch.countDown();
            }else if(eventType == Event.EventType.NodeCreated){
                //节点创建事件
                System.out.println("节点" + path + "被创建");
            }else if(eventType == Event.EventType.NodeDataChanged){
                //节点修改事件
                System.out.println("节点" + path + "被修改");

            }else if(eventType == Event.EventType.NodeDeleted){
                //节点删除事件
                System.out.println("节点" + path + "被删除");
            }
        }

    }
}

